<template>
  <PageCard title="表格对比工具">
    <div class="table-comparison-container">
      <!-- 文件上传区域 - 左右布局 -->
      <div class="upload-section">
        <n-grid :cols="24" :x-gap="24" :y-gap="24">
          <!-- 左侧：表格1上传区 -->
          <n-gi :span="isMobile ? 24 : 12">
            <n-card title="表格 1" :bordered="false" class="upload-card">
              <n-space vertical>
                <div class="upload-subtitle">上传第一个表格文件</div>
              <div v-if="!formValue.table1Url" class="upload-area">
                <n-upload
                  :action="uploadApi"
                  :max="1"
                  accept=".xlsx,.xls,.csv"
                  @finish="(args) => handleUploadFinish(args, 'table1')"
                  @before-upload="(data) => beforeUpload(data, 'table1')"
                  :show-file-list="false"
                  @error="handleUploadError"
                  :default-upload="false"
                >
                  <n-upload-dragger style="width: 100%; min-height: 200px;">
                    <div style="margin-bottom: 12px">
                      <n-icon size="36" :depth="3">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                          <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20M10,13H7V11H10V13M14,13H11V11H14V13M10,16H7V14H10V16M14,16H11V14H14V16M10,19H7V17H10V19M14,19H11V17H14V19Z" />
                        </svg>
                      </n-icon>
                    </div>
                    <n-text style="font-size: 14px;">
                      点击或拖拽上传第一个表格
                    </n-text>
                    <n-p depth="3" style="margin: 8px 0">
                      支持 Excel / CSV 格式
                    </n-p>
                  </n-upload-dragger>
                </n-upload>
              </div>
              <div v-else class="uploaded-file-info">
                <n-space align="center" justify="space-between">
                  <n-space align="center">
                    <n-icon size="20" color="#18a058">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M9,20.42L2.79,14.21L5.62,11.38L9,14.77L18.88,4.88L21.71,7.71L9,20.42Z" />
                      </svg>
                    </n-icon>
                    <span>{{ formValue.table1FileName || '表格1已上传' }}</span>
                  </n-space>
                  <n-button
                    size="small"
                    quaternary
                    @click="removeFile('table1')"
                  >
                    移除
                  </n-button>
                </n-space>
              </div>
            </n-space>
            </n-card>
          </n-gi>

          <!-- 右侧：表格2上传区 -->
          <n-gi :span="isMobile ? 24 : 12">
            <n-card title="表格 2" :bordered="false" class="upload-card">
              <n-space vertical>
                <div class="upload-subtitle">上传第二个表格文件</div>
              <div v-if="!formValue.table2Url" class="upload-area">
                <n-upload
                  :action="uploadApi"
                  :max="1"
                  accept=".xlsx,.xls,.csv"
                  @finish="(args) => handleUploadFinish(args, 'table2')"
                  @before-upload="(data) => beforeUpload(data, 'table2')"
                  :show-file-list="false"
                  @error="handleUploadError"
                  :default-upload="false"
                >
                  <n-upload-dragger style="width: 100%; min-height: 200px;">
                    <div style="margin-bottom: 12px">
                      <n-icon size="36" :depth="3">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                          <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20M10,13H7V11H10V13M14,13H11V11H14V13M10,16H7V14H10V16M14,16H11V14H14V16M10,19H7V17H10V19M14,19H11V17H14V19Z" />
                        </svg>
                      </n-icon>
                    </div>
                    <n-text style="font-size: 14px;">
                      点击或拖拽上传第二个表格
                    </n-text>
                    <n-p depth="3" style="margin: 8px 0">
                      支持 Excel / CSV 格式
                    </n-p>
                  </n-upload-dragger>
                </n-upload>
              </div>
              <div v-else class="uploaded-file-info">
                <n-space align="center" justify="space-between">
                  <n-space align="center">
                    <n-icon size="20" color="#18a058">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M9,20.42L2.79,14.21L5.62,11.38L9,14.77L18.88,4.88L21.71,7.71L9,20.42Z" />
                      </svg>
                    </n-icon>
                    <span>{{ formValue.table2FileName || '表格2已上传' }}</span>
                  </n-space>
                  <n-button
                    size="small"
                    quaternary
                    @click="removeFile('table2')"
                  >
                    移除
                  </n-button>
                </n-space>
              </div>
            </n-space>
            </n-card>
          </n-gi>
        </n-grid>
      </div>

      <!-- 配置选项 -->
      <n-card title="对比配置" :bordered="false" class="mt-4">
        <n-grid :cols="24" :x-gap="24" :y-gap="16">
          <n-gi :span="isMobile ? 24 : 12">
            <n-space vertical>
              <div class="config-label">列匹配方式</div>
              <n-radio-group v-model:value="formValue.config.columnMatchMode">
                <n-radio-button value="BY_INDEX">按列索引</n-radio-button>
                <n-radio-button value="BY_NAME">按列名</n-radio-button>
              </n-radio-group>
            </n-space>
          </n-gi>
          <n-gi :span="isMobile ? 24 : 12">
            <n-space vertical>
              <div class="config-label">对比选项</div>
              <n-space :vertical="isMobile" :size="isMobile ? 12 : 16">
                <n-checkbox v-model:checked="formValue.config.ignoreCase">
                  忽略大小写
                </n-checkbox>
                <n-checkbox v-model:checked="formValue.config.ignoreSpace">
                  忽略空格
                </n-checkbox>
                <n-space align="center" :size="4">
                  <n-checkbox v-model:checked="formValue.config.ignoreRowOrder">
                    忽略行顺序
                  </n-checkbox>
                  <n-tooltip>
                    <template #trigger>
                      <n-icon size="16" :depth="3" style="cursor: help;">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                          <path fill-rule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm8.706-1.442c1.146-.573 2.437.463 2.126 1.706l-.709 2.836.042-.02a.75.75 0 01.67 1.34l-.04.022c-1.147.573-2.438-.463-2.127-1.706l.71-2.836-.042.02a.75.75 0 11-.671-1.34l.041-.022zM12 9a.75.75 0 100-1.5.75.75 0 000 1.5z" clip-rule="evenodd" />
                        </svg>
                      </n-icon>
                    </template>
                    基于行内容进行匹配，适用于行顺序不同但内容相同的表格
                  </n-tooltip>
                </n-space>
              </n-space>
            </n-space>
          </n-gi>
        </n-grid>
      </n-card>

      <!-- 操作按钮 -->
      <div class="action-bar">
        <n-button
          type="primary"
          size="large"
          :loading="loading"
          :disabled="!formValue.table1Url || !formValue.table2Url"
          @click="handleCompare"
        >
          开始对比
        </n-button>
        <n-button
          size="large"
          :disabled="!comparisonResult"
          @click="handleReset"
        >
          重置
        </n-button>
      </div>

      <!-- 对比结果弹框 -->
      <TableComparisonModal
        v-model="showComparisonModal"
        :result="comparisonResult"
        :loading="loading"
        @download="handleDownload"
      />
    </div>

    <n-divider />

    <!-- 使用说明 -->
    <UsageGuide
      :title="usageGuideConfig.title"
      :steps="usageGuideConfig.steps"
      :tips="usageGuideConfig.tips"
      :example="usageGuideConfig.example"
    />
  </PageCard>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useMessage, type UploadFileInfo } from 'naive-ui'
import PageCard from '@/components/PageCard.vue'
import UsageGuide from '@/components/UsageGuide.vue'
import TableComparisonModal from './TableComparisonModal.vue'
import { compareTable } from '@/api/utility/tableComparison'
import type { ComparisonResult, ComparisonConfig } from '@/api/utility/tableComparison'
import { useBreakpoint } from '@/utils/responsive-helper'
import { uploadApi } from '@/api/oss'

const { isMobile } = useBreakpoint()
const message = useMessage()
const loading = ref(false)
const comparisonResult = ref<ComparisonResult | null>(null)
const showComparisonModal = ref(false)

// UsageGuide configuration
const usageGuideConfig = {
  title: '使用说明',
  steps: [
    '分别上传两个需要对比的表格文件（Excel或CSV格式）',
    '选择列匹配方式：按列索引或按列名',
    '配置对比选项：是否忽略大小写、空格等',
    '点击"开始对比"按钮查看结果'
  ],
  tips: [
    '支持Excel（.xlsx/.xls）和CSV格式的表格文件',
    '系统会自动识别并展示新增、删除、修改的行数据',
    '对比结果包含详细的差异分析和统计信息'
  ],
  example: '对比两个版本的产品清单，查看价格变动和新增/删除的产品'
}

const formValue = ref({
  table1Url: '',
  table2Url: '',
  table1FileName: '',
  table2FileName: '',
  config: {
    ignoreRowOrder: false,
    columnMatchMode: 'BY_INDEX' as 'BY_INDEX' | 'BY_NAME',
    ignoreCase: false,
    ignoreSpace: false
  } as ComparisonConfig
})

const beforeUpload = (data: {
  file: UploadFileInfo
  fileList: UploadFileInfo[]
}, tableType: 'table1' | 'table2') => {
  const file = data.file.file
  if (!file) return false

  // 检查文件类型
  const fileName = file.name.toLowerCase()
  const isValidType = fileName.endsWith('.xlsx') || fileName.endsWith('.xls') || fileName.endsWith('.csv')
  if (!isValidType) {
    message.error('请上传Excel或CSV格式的表格文件')
    return false
  }



  // 手动处理上传
  handleUploadAction(data, tableType)
  return false
}

const handleUploadAction = async (data: {
  file: UploadFileInfo
  fileList: UploadFileInfo[]
}, tableType: 'table1' | 'table2') => {
  const file = data.file.file
  if (!file) return

  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await fetch(uploadApi as string, {
      method: 'POST',
      body: formData
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()

    if (result.code === 200) {
      if (tableType === 'table1') {
        formValue.value.table1Url = result.data
        formValue.value.table1FileName = file.name
      } else {
        formValue.value.table2Url = result.data
        formValue.value.table2FileName = file.name
      }
      message.success(`${tableType === 'table1' ? '表格1' : '表格2'}上传成功`)
    } else {
      message.error(result.message || '上传失败')
    }
  } catch (error) {
    console.error('Upload error:', error)
    message.error('上传失败：请确保后端服务已启动')
  }
}

const handleUploadFinish = (
  { file, event }: { file: UploadFileInfo; event?: ProgressEvent },
  tableType: 'table1' | 'table2'
) => {
  try {
    const response = (event?.currentTarget as XMLHttpRequest)?.response
    if (response) {
      const parse = JSON.parse(response)
      if (parse.code === 200) {
        if (tableType === 'table1') {
          formValue.value.table1Url = parse.data
          formValue.value.table1FileName = file.name
        } else {
          formValue.value.table2Url = parse.data
          formValue.value.table2FileName = file.name
        }
        message.success(`${tableType === 'table1' ? '表格1' : '表格2'}上传成功`)
      } else {
        message.error(parse.message || '上传失败')
      }
    }
  } catch (error) {
    console.error('Upload error:', error)
    message.error('上传失败：请确保后端服务已启动')
  }
  return file
}

const handleUploadError = (error: Error) => {
  console.error('Upload component error:', error)
  message.error('上传错误：' + error.message)
}

const removeFile = (tableType: 'table1' | 'table2') => {
  if (tableType === 'table1') {
    formValue.value.table1Url = ''
    formValue.value.table1FileName = ''
  } else {
    formValue.value.table2Url = ''
    formValue.value.table2FileName = ''
  }
  comparisonResult.value = null
}

const handleCompare = async () => {
  if (!formValue.value.table1Url || !formValue.value.table2Url) {
    message.warning('请先上传两个表格文件')
    return
  }

  try {
    loading.value = true
    showComparisonModal.value = true

    const result = await compareTable({
      table1Url: formValue.value.table1Url,
      table2Url: formValue.value.table2Url,
      config: formValue.value.config
    })

    comparisonResult.value = result
    message.success('表格对比完成')
  } catch (error: any) {
    showComparisonModal.value = false
    if (error?.message) {
      message.error(error.message)
    } else {
      message.error('对比失败，请检查输入的URL是否正确')
    }
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  formValue.value = {
    table1Url: '',
    table2Url: '',
    table1FileName: '',
    table2FileName: '',
    config: {
      ignoreRowOrder: false,
      columnMatchMode: 'BY_INDEX',
      ignoreCase: false,
      ignoreSpace: false
    }
  }
  comparisonResult.value = null
  showComparisonModal.value = false
}

const handleDownload = () => {
  message.info('下载功能开发中...')
}
</script>

<style scoped lang="less">
.table-comparison-container {
  max-width: 1400px;
  margin: 0 auto;
}

.upload-section {
  margin-bottom: 24px;
}

.upload-card {
  height: 100%;

  .upload-subtitle {
    font-size: 14px;
    color: var(--n-text-color2);
    margin-bottom: 12px;
  }
}

.config-label {
  font-weight: 500;
  color: var(--n-text-color2);
  margin-bottom: 8px;
}

.upload-area {
  width: 100%;
}

.action-bar {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin: 24px 0;

  @media (max-width: 768px) {
    flex-direction: column;

    .n-button {
      width: 100%;
    }
  }
}

.mt-4 {
  margin-top: 16px;
}

:deep(.n-upload-dragger) {
  background: #fafafa;
  border: 2px dashed #d9d9d9;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;

  @media (prefers-color-scheme: dark) {
    background: rgba(255, 255, 255, 0.04);
    border-color: rgba(255, 255, 255, 0.2);
  }

  &:hover {
    border-color: var(--primary-color);
    background: #f5f5f5;

    @media (prefers-color-scheme: dark) {
      background: rgba(255, 255, 255, 0.08);
      border-color: var(--primary-color);
    }
  }
}

.uploaded-file-info {
  padding: 12px 16px;
  background: #f0f2f5;
  border-radius: 6px;

  @media (prefers-color-scheme: dark) {
    background: rgba(255, 255, 255, 0.08);
  }
}
</style>
